@extends('layouts.admin.base')

@section('title', '权限管理')

@section('content')
    <style>
        .layui-table-tool-temp {
            padding: 0;
        }

    </style>

    <div class="layui-body" >
        <!-- 导航区域 -->
        <div class="nav-area">
            <span class="nav">系统管理——权限配置</span>
        </div>
        <!-- 搜索查询区域 -->
        <!-- <div class="search-area">
            <form id="qryForm"  class="layui-form layui-form-pane" action="">
                <div class="layui-inline search-input">
                    <label class="layui-form-label">角色名称</label>
                    <div class="layui-input-inline" >
                        <input type="text" name="rolename" class="layui-input" autocomplete="off">
                    </div>
                </div>
                <div class="layui-inline search-input">
                    <button type="button" lay-submit lay-filter="queryBtn" class="layui-btn layui-btn-normal">查询</button>
                    <button type="button" lay-submit lay-filter="resetBtn" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </form>
        </div> -->
        <!-- 内容主体区域 -->
        <div class="show-area">
            <form class="layui-form" lay-filter="tableForm">
                <table class="layui-table" >
                    <thead>
                    <tr>
                        <th style="text-align: center">功能模块</th>
                        <th style="text-align: center">操作节点</th>
                        @foreach($result['role_data'] as $role)
                            <th style="text-align: center">{{$role['rolename']}}</th>
                        @endforeach
                    </tr>
                    </thead>
                    <tbody id="tbody-list">
                    @foreach($result['admin_data'] as $k => $module)
                        <tr>
                            <td style="text-align: center" rowspan="{{ collect($module['children'])->map(function($item) { return collect($item['children'])->count(); })->sum() }}" title="{{$module['id']}}">{{$module['title']}}</td>

                            @if ($module['children'][0]['id'] == $module['children'][0]['children'][0]['id'])
                                <td style="text-align: left" title="{{$module['children'][0]['children'][0]['id']}}">{{$module['children'][0]['title']}}————{{$module['children'][0]['children'][0]['title']}}</td>
                            @else
                                <td style="text-align: left;padding-left: 100px;" title="{{$module['children'][0]['children'][0]['id']}}">{{$module['children'][0]['title']}}————{{$module['children'][0]['children'][0]['title']}}</td>
                            @endif
                            @foreach($result['role_data'] as $role)
                                <td style="text-align: center"><input name="actionid" lay-filter="actionids" lay-skin="primary" type="checkbox" class="layui-form-checkbox" @if(in_array($module['children'][0]['children'][0]['id'],$role['rolepowers'])) checked @endif value="{{$role['roleid']}}_{{$module['children'][0]['children'][0]['id']}}"></td>
                            @endforeach
                        </tr>
                        @php unset($module['children'][0]['children'][0]);@endphp
                        @foreach($module['children'] as $key => $child)
                            @if (collect($child['children'])->count() > 0)
                                @foreach($child['children'] as $gk => $gc)
                                    <tr>
                                        @if ($child['id'] == $gc['id'])
                                            <td style="text-align: left" title="{{$gc['id']}}">{{$child['title']}}————{{$gc['title']}}</td>
                                        @else
                                            <td style="text-align: left;padding-left: 100px;" title="{{$gc['id']}}">{{$child['title']}}————{{$gc['title']}}</td>
                                        @endif
                                        @foreach($result['role_data'] as $role)
                                            <td style="text-align: center"><input name="actionid" lay-filter="actionids" lay-skin="primary" type="checkbox" class="layui-form-checkbox" @if(in_array($gc['id'],$role['rolepowers'])) checked @endif value="{{$role['roleid']}}_{{$gc['id']}}"></td>
                                        @endforeach
                                    </tr>
                                @endforeach
                            @endif
                        @endforeach
                    @endforeach
                    </tbody>
                </table>
                <div class="layui-row" style="text-align: center">
                    <button  class="layui-btn layui-btn-normal" lay-submit lay-filter="submit">提交</button>
                </div>
            </form>
            <div class="pagebarbox" style="text-align: end"><div id="pageBar" class="pagebar"></div></div>

            <script type="text/html" id="toolbarDemo">
                <div class="layui-btn-container" style="float: right">
                    <button id="addBtn" class="layui-btn layui-btn-normal layui-btn-sm" lay-event="addBtn" btnPermission="700202">添加</button>
                </div>
            </script>
        </div>
        <script type="text/html" id="opDemo">
            <button class="layui-btn layui-btn-normal layui-btn-line-height" lay-event="edit" btnPermission="700203">编辑</button>
            @{{# if(d.status == '1'){ }}
            <button class="layui-btn layui-btn-checked layui-btn-line-height" lay-event="setStatus" btnPermission="700204">启用</button>
            @{{# }else{  }}
            <button class="layui-btn layui-btn-danger layui-btn-line-height" lay-event="setStatus" btnPermission="700204">禁用</button>
            @{{# }  }}
            <button class="layui-btn layui-btn-normal layui-btn-line-height" lay-event="power" btnPermission="700205">权限分配</button>
        </script>






    </div>
    <!-- 权限设置界面 -->
    <div id="setRolePower" style="display: none;padding: 20px">
        <div id="powerTree"></div>

        <div style="text-align: center; clear: both;">
            <button class="layui-btn  layui-btn-normal" lay-submit lay-filter="powerSubmit" style="padding: 0 50px; margin-top: 20px;">提交</button>
        </div>
    </div>
    <!-- 编辑界面 -->
    <div id="editRole" style="display: none;padding: 20px">
        <form class="layui-form" action="" id="editForm" lay-filter="editForm">
            <div class="layui-form-item">
                <label class="layui-form-label"><i class="redstar">*</i>角色名称</label>
                <div class="layui-input-inline">
                    <input type="text" name="rolename" required lay-verify="required" placeholder="请输入角色名称" lay-reqText="角色名称不能为空" autocomplete="off" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label"><i class="redstar">*</i>角色描述</label>
                <div class="layui-input-inline">
                    <input type="text" name="roledes" required lay-verify="required" placeholder="请输入角色描述" lay-reqText="角色描述不能为空" autocomplete="off" class="layui-input">
                </div>
            </div>

            <!--<div class="layui-form-item text-center">-->
            <div style="text-align: center; clear: both;">
                <button class="layui-btn  layui-btn-normal" lay-submit lay-filter="editSubmit" style="padding: 0 50px; margin-top: 20px;">提交</button>
            </div>
            <!--</div>-->

        </form>
    </div>
    <!-- 新增界面 -->
    <div id="addRole" style="display: none;padding: 20px">
        <form class="layui-form" action="" id="addForm" lay-filter="addForm">
            <div class="layui-form-item" >
                <label class="layui-form-label" style="text-align: left"><i class="redstar">*</i>角色名称</label>
                <div class="layui-input-block">
                    <input type="text" name="rolename" required lay-verify="required" placeholder="请输入角色名称" lay-reqText="角色名称不能为空" autocomplete="off" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label" style="text-align: left"><i class="redstar">*</i>角色描述</label>
                <div class="layui-input-block">
                    <textarea type="text" name="roledes" rows="3" placeholder="请输入角色描述" autocomplete="off" class="layui-textarea"></textarea>
                </div>
            </div>

            <!--<div class="layui-form-item text-center">-->
            <div style="text-align: center; clear: both;">
                <button class="layui-btn  layui-btn-normal" lay-submit lay-filter="addSubmit" style="padding: 0 50px; margin-top: 20px;">提交</button>
            </div>
            <!--</div>-->

        </form>
    </div>
@endsection

@section('script')
<style>
    #powerTree .layui-tree {
        border: 1px solid #eee;
        padding: 10px 5px;
        text-align: left;
    }
    .layui-tree span {
        font-size: 14px;
    }
    .layui-tree>.layui-tree-set {
        margin-bottom: 30px;
    }
    .layui-tree>.layui-tree-set>.layui-tree-pack>.layui-tree-set {
        margin-bottom: 50px;
    }
    .layui-tree .layui-tree-set .layui-tree-pack .layui-tree-set .layui-tree-pack .layui-tree-set .layui-tree-entry {
        float : left;
    }
</style>
    <script>
        var totalNUm = 0;
        var table;
        var form;
        var laypage;
        var layer;
        var filters = '';
        var addLayer;
        var editLayer;
        var powerLayer;
        var id = '';
        var util;
        var laytpl;
        var tableData;
        var element;
        var per_page = 10;
        var tree;
        $(function(){
            layui.use(['table', 'form', 'element', 'laypage','tree','util','laytpl'], function() {
                table = layui.table;
                element = layui.element;
                form = layui.form;
                laypage = layui.laypage;
                layer = layui.layer;
                tree = layui.tree;
                util = layui.util;
                laytpl = layui.laytpl;
                var actionids = [];

                //getList(1,per_page);

                table.on('toolbar(tablelsit)', function(obj){
                    switch(obj.event){
                        case 'addBtn':
                            layer.ready(function() {
                                var index = layer.load(2);
                                addLayer = layer.open({
                                    type: 1,
                                    title: '添加角色',
                                    content: $('#addRole'),
                                    area: ['640px', '510px'],
                                    cancel: function() {
                                        //右上角关闭回调
                                        $('#addForm')[0].reset()
                                        //return false 开启该代码可禁止点击该按钮关闭
                                    }
                                });
                                layer.close(index);
                            });
                            break;
                    }
                });

                // 搜索查询
                form.on('submit(queryBtn)', function(data) {
                    var param = data.field;
                    filters = param
                    getList(1,per_page)
                });
                // 重置
                form.on('submit(resetBtn)', function(data) {
                    filters = {};
                    $('#qryForm')[0].reset();
                    getList(1,per_page)
                });

                // 新增提交
                form.on('submit(addSubmit)', function(data) {
                    var data = data.field;
                    var para = {
                        "rolename": data.rolename,
                        "roledes": data.roledes,
                    }
                    addRole(para, function(res) {
                        if(res.code === 1) {
                            layer.close(addLayer);
                            $('#addForm')[0].reset()
                            layer.msg(res.msg, {
                                time: 2000,
                                icon: 6
                            });
                            getList(1);
                        } else {
                            layer.msg(res.msg, {
                                time: 2000,
                                icon: 5
                            });
                        }
                    })
                    return false;
                });

                // 编辑提交
                form.on('submit(editSubmit)', function(data) {
                    var data = data.field;
                    var para = {
                        "id": id,
                        "rolename": data.rolename,
                        "roledes": data.roledes,
                    }
                    editRole(para, function(res) {
                        if(res.code === 1) {
                            layer.close(editLayer);
                            $('#editForm')[0].reset();
                            layer.msg(res.msg, {
                                time: 2000,
                                icon: 6
                            });
                            getList(1);
                        } else {
                            layer.msg(res.msg, {
                                time: 2000,
                                icon: 5
                            });
                        }
                    });

                    return false;
                });

                // 权限设置提交
                form.on('submit(powerSubmit)', function(data) {
                    actionids = [];
                    var checkedData = tree.getChecked('ptree');
                    getCheckedAction(checkedData);
                    var para = {
                        "id": id,
                        "actionids": actionids,
                    }
                    setRolePowers(para, function(res) {
                        if(res.code === 1) {
                            layer.close(powerLayer);
                            layer.msg(res.msg, {
                                time: 2000,
                                icon: 6
                            });
                        } else {
                            layer.msg(res.msg, {
                                time: 2000,
                                icon: 5
                            });
                        }
                    });

                    return false;
                });

                form.on('checkbox(actionids)', function(obj){
                  if (obj.elem.checked){
                      actionids.push({"name":obj.value,"is_checked":"1"});
                  }else{
                      actionids.push({"name":obj.value,"is_checked":"0"});
                  }
                });

                form.on('submit(tableForm)',function (data) {
                    setRolePowers({"actionids":actionids},function (res) {
                        if (res.code === 1){
                            layer.msg(res.msg, {
                                time: 2000,
                                icon: 6
                            },function(){
                                location.reload();
                            });

                        }else{
                            layer.msg(res.msg, {
                                time: 2000,
                                icon: 5
                            });
                        }
                    });
                    return false;
                })

                table.on('tool(tablelsit)', function(obj) {
                    var data = obj.data;
                    id = data.id;

                    if(obj.event === 'edit') { //设置角色弹窗
                        layer.ready(function() {
                            var index = layer.load(2);
                            editLayer = layer.open({
                                type: 1,
                                title: "编辑",
                                content: $('#editRole'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                                area: ['485px', '300px'],
                                cancel: function() {
                                    //右上角关闭回调
                                    $('#editForm')[0].reset()
                                    //return false 开启该代码可禁止点击该按钮关闭
                                }
                            });
                            layer.close(index);
                        });
                        //获取编辑的值
                        form.val('editForm', {
                            "rolename": data.rolename,
                            "roledes": data.roledes
                        });

                    } else if(obj.event === 'power') {
                        var index = layer.load(2);
                        var role_id = obj.data.id;
                        powerLayer = layer.open({
                            type: 1,
                            title: '权限设置',
                            content: $('#setRolePower'),
                            area: ['100%',"100%"],
                        });
                        layer.close(index);
                       renderPowerTree(role_id);
                    } else if(obj.event === 'setStatus'){
                        if (obj.data.status == '1') {
                            var msg  = '确认禁用吗?';
                        } else {
                            var msg = '确认启用吗?';
                        }
                        layer.confirm(msg, function(index) {
                            var para = {
                                "id": obj.data.id,
                            };
                            if (obj.data.status == '1') {
                                para.status = '2';
                            } else {
                                para.status = '1';
                            }
                            setRoleStatus(para, function (res) {
                                if (res.code === 1) {
                                    layer.msg(res.msg, {
                                        time: 2000,
                                        icon: 6
                                    });
                                    getList(curr_page, per_page);
                                } else {
                                    layer.msg(res.msg, {
                                        time: 2000,
                                        icon: 5
                                    });

                                }
                            })
                        });
                    }
                });
            });
        });

        // 渲染权限树
        function renderPowerTree(role_id) {
            var para = {role_id:role_id};
            getPowerTree(para, function(res){
                if(res.code === 1) {

                    tree.render({
                        elem: '#powerTree',
                        data: res.data,
                        id: 'ptree',
                        showCheckbox: true,
                        showLine: false
                    });
                    checkRolePower();
                } else {
                    layer.msg(res.msg, {
                        time: 2000,
                        icon: 5
                    });
                }
            });
        }

        // 设置角色权限选中状态
        function checkRolePower() {
            var para = {
                "id": id,
            };
            getRolePowers(para, function(res){
                if(res.code == 1) {
                    tree.setChecked('ptree', res.data);
                } else {
                    layer.msg(res.msg, {
                        time: 2000,
                        icon: 5
                    });
                }
            });
        }

        function getCheckedAction(checkedData){
            for(var i=0;i<checkedData.length;i++){
                var item = checkedData[i];
                var children = item['children'];
                if(children){
                    getCheckedAction(children);
                }else{
                    actionids.push(item['id']);
                }
            }
        }

        // 获取页面数据
        function getList(page,limit) {
            if (filters == ''){
                filters = {}
            }
            var para = {
                "page": page,
                "filters": filters,
                "limit": limit
            };
            getRoleList(para, function(res){
                if(res.code === 1) {
                    if(totalNUm != res.total) {
                        totalNUm = res.total;
                        per_page = res.limit;
                        renderPageBar(page,per_page)
                    }

                    table.render({
                        data: res.data,
                        elem: '#tablelsit',
                        toolbar: '#toolbarDemo',
                        defaultToolbar: [],
                        limit: res.limit,
                        cols: [
                            [{
                                field: 'id',
                                title: '序号',
                                width: '8%',
                                align: 'center',
                                templet: function (data) {
                                    var curPage = $(".layui-laypage-skip .layui-input").val();
                                    return (curPage-1)*10 + data.LAY_INDEX;
                                },
                            },{
                                field: 'rolename',
                                title: '角色名称',
                                width: '20%',
                                align: 'center'
                            },{
                                field: 'roledes',
                                title: '角色描述',
                                width: '30%',
                                align: 'center'
                            },{
                                field: 'op_total',
                                title: '权限数量',
                                width: '8%',
                                align: 'center'
                            },{
                                field: 'user_total',
                                title: '用户数量',
                                width: '8%',
                                align: 'center'
                            },{
                                title: '操作',
                                align: 'center',
                                toolbar: '#opDemo'
                            }]
                        ],
                        id:"tableIns",
                        done: function(res, curr, count) {
                            setBtnPermission();
                            tableData = table.cache.tableIns;
                        },
                        page: false,
                        loading: true
                    });
                } else {
                    layer.msg(res.msg, {
                        time: 2000,
                        icon: 5
                    });
                }
            });

        }

        // 渲染页面
        function renderPageBar(page,limit) {
            laypage.render({
                elem: 'pageBar',
                count: totalNUm, //数据总数，从服务端得到
                curr: page,
                first: '第一页',
                last: '最后一页',
                limit:limit,
                layout: ['limit','count', 'prev', 'page', 'next', 'skip'],
                jump: function(obj, first) {
                    //首次不执行
                    if(!first) {
                        layer.closeAll();
                        getList(obj.curr,obj.limit)
                    }
                }
            });
        }

    </script>
@endsection


